﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Data.SqlServerCe;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintProducts();
            PrintProductsByDynamicObj();

            Console.ReadKey();
        }

        private static void PrintProductsByDynamicObj()
        {
            Stopwatch sw = Stopwatch.StartNew();

            dynamic reader = new DynamicReader(GetDbReader());

            while (reader.Read())
            {
                string name = reader.name;
                string model = reader.model;
                double? price = reader.price;

                Console.Write("{0}\t{1}\t{2}\n", name, model, price.HasValue ? price.Value : 0);
            }
            Console.WriteLine("Time Elapse:{0}", sw.ElapsedMilliseconds);
            
        }

        private static void PrintProducts()
        {
            Stopwatch sw = Stopwatch.StartNew();

            SqlCeDataReader reader =  GetDbReader();
            while (reader.Read())
            {
                string name = reader["name"] as string;
                string model = reader["model"] as string;

                decimal? price;
                object t = reader["price"];
                if (t == DBNull.Value)
                    price = null;
                else
                    price = Decimal.Parse(t.ToString());

                Console.Write("{0}\t{1}\t{2}\n", name, model, price.HasValue ? price.Value : 0);
            }
            Console.WriteLine("Time Elapse:{0}",sw.ElapsedMilliseconds);
        }



        private static SqlCeDataReader GetDbReader()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data Source=./Data/Database1.sdf");
            conn.Open();
            var cmd = conn.CreateCommand();
            cmd.CommandText = "select name,model,price from product";
            var reader = cmd.ExecuteReader();

            return reader;
        }
    }
}
